package lib.bone.system.module.log;

import cn.hutool.core.lang.Validator;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.PageResultDTO;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class SysLogServiceImpl implements SysLogService{

    @Autowired
    SysLogDAO dao;

    @Override
    public PageResultDTO<SysLog> getAll(Pageable pageable, Example<SysLog> example) {
        Page<SysLog> page;
        //是否为空 --
        if(Validator.isEmpty(example)){
            page = dao.findAll(pageable);
        }else {
            page = dao.findAll(example,pageable);
        }
        List<SysLog> list = page.getContent();
        PageResultDTO<SysLog> pageResultDTO = new PageResultDTO<>();
        pageResultDTO.setContent(list);
        pageResultDTO.setSize(page.getSize());
        pageResultDTO.setTotalPages(page.getTotalPages());
        pageResultDTO.setNumber(page.getNumber());
        pageResultDTO.setTotalElements(page.getTotalElements());

        return pageResultDTO;
    }

    @Override
    public ResponseDTO<SysLog> deleteById(Long id) {
        Optional<SysLog> sysLogOp = dao.findById(id);
        if(!sysLogOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID:["+id+"]对应数据不存在");
        dao.deleteById(id);
        return ResponseDTO.succMsg("删除成功!");
    }

    @Override
    public Optional<SysLog> getById(Long id) {
        return dao.findById(id);
    }

    @Override
    public SysLog saveOne(SysLog sysLog) {
        if (Validator.isNotEmpty(sysLog.getId())){
            throw new BusinessException(ResponseCodeConst.ERROR_PARAM);
        }
        return dao.save(sysLog);
    }

    @Override
    public SysLog updateOne(SysLog sysLog) {
        if (Validator.isEmpty(sysLog.getId())){
            throw new BusinessException(ResponseCodeConst.ERROR_PARAM);
        }
        return dao.save(sysLog);
    }
}
